package ai.people.netmon.msgsearch.grpcservice;

import ai.people.core.grpc.lib.es.SearchAccountGrpcRequest;
import ai.people.core.grpc.lib.es.SearchAccountPageResponse;
import ai.people.core.grpc.lib.es.SearchAccountServiceGrpc;
import ai.people.core.grpc.utils.ProtoJsonUtil;
import ai.people.core.grpc.utils.StreamObserverDelegate;
import ai.people.netmon.framework.domain.searchmsg.request.SearchAccountRequest;
import ai.people.netmon.framework.domain.searchmsg.vo.SearchAccountVO;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.msgsearch.service.AccountSearchService;
import com.alibaba.fastjson.JSON;
import io.grpc.stub.StreamObserver;
import lombok.RequiredArgsConstructor;
import net.devh.boot.grpc.server.service.GrpcService;

import java.io.IOException;

/**
 * 搜索账户grpc服务
 *
 * @author yuanqinglong
 * @date 2022/8/4 10:56
 */
@GrpcService
@RequiredArgsConstructor
public class SearchAccountGrpcService extends SearchAccountServiceGrpc.SearchAccountServiceImplBase {

    private final AccountSearchService accountSearchServiceImpl;

    /**
     * 搜索账户
     *
     * @param request          请求
     * @param responseObserver 响应观察者
     */
    @Override
    public void searchAccount(SearchAccountGrpcRequest request, StreamObserver<SearchAccountPageResponse> responseObserver) {
        StreamObserverDelegate.build(responseObserver).execute(() -> {
            SearchAccountRequest searchAccountRequest = ProtoJsonUtil.toJava(request, SearchAccountRequest.class);
            try {
                PageResponse<SearchAccountVO> searchAccountVOPageResponse = accountSearchServiceImpl.searchAccount(searchAccountRequest);
                return (SearchAccountPageResponse)ProtoJsonUtil.toProtoMessage(SearchAccountPageResponse.newBuilder(), JSON.toJSONString(searchAccountVOPageResponse));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 搜索标签帐户
     * <pre>
     * 查询预警账号、被打了标签的账号
     * </pre>
     *
     * @param request          请求
     * @param responseObserver 响应观察者
     */
    @Override
    public void searchLabelAccount(SearchAccountGrpcRequest request, StreamObserver<SearchAccountPageResponse> responseObserver) {
        StreamObserverDelegate.build(responseObserver).execute(() -> {
            SearchAccountRequest searchAccountRequest = ProtoJsonUtil.toJava(request, SearchAccountRequest.class);
            try {
                PageResponse<SearchAccountVO> searchAccountVOPageResponse = accountSearchServiceImpl.searchLabelAccount(searchAccountRequest);
                return (SearchAccountPageResponse)ProtoJsonUtil.toProtoMessage(SearchAccountPageResponse.newBuilder(), JSON.toJSONString(searchAccountVOPageResponse));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}
